<template>
    <div class="app-container">
        <!-- <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" @change="handleDateChange" style="width: 100%;" />
                </el-col>
                <el-col :span="6">
                    <el-select v-model="selectedArea" placeholder="请选择区域">
                        <el-option v-for="item in areas" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-col>
            </el-row>
        </el-card> -->

        <el-card>
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="时间维度" style="width: 300px;">
                    <el-select v-model="searchForm.timeDimension" placeholder="请选择时间维度">
                        <el-option label="天" :value="1" />
                        <el-option label="月" :value="2" />
                        <el-option label="年" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                    <el-date-picker v-model="searchForm.time" v-if="searchForm.timeDimension == 1" type='date'
                        placeholder="选择时间" value-format="YYYY-MM-DD" />
                    <el-date-picker v-model="searchForm.time" v-if="searchForm.timeDimension == 2" type="month"
                        placeholder="选择时间" value-format="YYYY-MM" />
                    <el-date-picker v-model="searchForm.time" v-if="searchForm.timeDimension == 3" type='year'
                        placeholder="选择时间" value-format="YYYY" />
                </el-form-item>
                <el-form-item label="区域">
                    <el-select v-model="searchForm.region" placeholder="请选择区域" style="width: 300px;">
                        <el-option v-for="item in regionOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 指标卡片 -->
        <el-row :gutter="20" class="mt-2">
            <el-col :span="8">
                <el-card>
                    <div class="site-info">
                        <div>
                            <h3>PH值合格率</h3>
                            <div class="num">
                                {{ overviewData.phQualityRate }}%
                            </div>
                        </div>
                        <div class="loading-circle">
                            <CircularProgressBar :size="100" :value="overviewData.phQualityRate" :stroke-width="10"
                                color="#3b82f6" />
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card>
                    <div class="site-info">
                        <div>
                            <h3>浊度合格率</h3>
                            <div class="num">
                                {{ overviewData.turbidityQualityRate }}%
                            </div>
                        </div>
                        <div class="loading-circle">
                            <CircularProgressBar :size="100" :value="overviewData.turbidityQualityRate"
                                :stroke-width="10" color="#10b981" />
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card>
                    <div class="site-info">
                        <div>
                            <h3>余氯合格率</h3>
                            <div class="num">
                                {{ overviewData.chlorineQualityRate }}%
                            </div>
                        </div>
                        <div class="loading-circle">
                            <CircularProgressBar :size="100" :value="overviewData.chlorineQualityRate"
                                :stroke-width="10" color="#ef4444" />
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 第一行布局 -->
        <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="12">
                <el-card>
                    <Echarts :option="pieChartOptions" height="400px" />
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card>
                    <Echarts :option="barChartOptions" height="400px" />
                </el-card>
            </el-col>
        </el-row>

        <!-- 第二行布局 -->
        <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="12">
                <el-card>
                    <el-table :data="sisDetailList" style="width: 100%">
                        <el-table-column prop="date" label="日期"></el-table-column>
                        <el-table-column prop="siteName" label="站点名称"></el-table-column>
                        <el-table-column prop="overallRate" label="综合合格率"></el-table-column>
                        <el-table-column prop="phRate" label="pH 合格率"></el-table-column>
                        <el-table-column prop="turbidityRate" label="浊度 合格率"></el-table-column>
                        <el-table-column prop="chlorineRate" label="余氯 合格率"></el-table-column>
                        <el-table-column prop="mainAbnormal" label="主要异常指标"></el-table-column>
                        <el-table-column prop="abnormalPct" label="异常占比"></el-table-column>
                    </el-table>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card>
                    <Echarts :option="lineChartOptions" height="400px" />
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import CircularProgressBar from '@/components/CircularProgressBar'
import Echarts from '@/components/ECharts'
import {
    getWaterQualityOverview,
    getSingleQualityRate,
    getQualifiedRateTrend,
    getRegionList,
    getTrendAnalysisDetail,
    getAbnormalProportion
} from '@/api/dispatch/analyze/water_quality_topics'
import dayjs from 'dayjs'

// 搜索表单
const searchForm = reactive({
    timeDimension: 1, // 1-天维度 2-月维度 3-年维度
    dateRange: '',
    region: '',
    time: '',
})
const regionOptions = ref([])
const sisDetailList = ref([])
const singleQualityRate = ref([])
// 数据状态
const overviewData = reactive({
    comprehensiveQualityRate: 0,
    turbidityQualityRate: 0,
    chlorineQualityRate: 0,
    phQualityRate: 0
})
const abnormalProportionData = ref([])
const qualifiedRateTrendData = ref([])

// 计算图表配置
const pieChartOptions = computed(() => {
    return {
        title: {
            text: '水质指标异常占比',
            left: 'center'
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            data: abnormalProportionData.value.map(item => item.name)
        },
        series: [
            {
                name: '水质指标异常占比',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '18',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: abnormalProportionData.value.map(item => ({
                    value: item.value,
                    name: item.name
                }))
            }
        ]
    }
})

const barChartOptions = computed(() => {
    // 这里可以根据实际数据生成柱状图配置
    return {
        title: {
            text: '单项水质合格率',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01],
            axisLabel: {
                formatter: '{value}%'
            }
        },
        yAxis: {
            type: 'category',
            data: singleQualityRate.value.map(item => item.date)
        },
        series: [
            {
                name: '水质合格率',
                type: 'bar',
                data:singleQualityRate.value.map(item => item.value)
            }
        ]
    }
})

const lineChartOptions = computed(() => {
    console.log(qualifiedRateTrendData.value);
    
    return {
        title: {
            text: '水质合格率趋势',
            left: 'left'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' },
        },
        legend: {
            data: qualifiedRateTrendData?.value.map(item => item.label),
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: qualifiedRateTrendData?.value[0]?.points.map(item => item.date.split(' ')[1])
        },
        yAxis: {
            type: 'value',
            axisLabel: { formatter: '{value}%' }
        },
        series: qualifiedRateTrendData.value.map(item => ({
            name: item.label,
            type: 'line',
            smooth: true,
            symbolSize: 6,
            lineStyle: { width: 3 },
            emphasis: { focus: 'series' },
            data: item.points.map(child => child.value)
        }))
    };

})
// 处理搜索
const handleSearch = () => {
    fetchAllData()
}
// 获取所有数据
const fetchAllData = async () => {
    const overviewRes = await getWaterQualityOverview(searchForm);
    const qualityRate = await getSingleQualityRate(searchForm);
    const trendRes = await getQualifiedRateTrend(searchForm);
    const sisDetail = await getTrendAnalysisDetail(searchForm);
    const proportionRes = await getAbnormalProportion(searchForm);
    Object.assign(overviewData, overviewRes.data);
    singleQualityRate.value = qualityRate.data;
    abnormalProportionData.value = proportionRes.data;
    qualifiedRateTrendData.value = trendRes.data;
    sisDetailList.value = sisDetail.data;
}

// 初始化加载数据
onMounted(async () => {
    const regionList = await getRegionList();
    regionOptions.value = regionList.data;
    searchForm.region = regionList.data[0].id;

    searchForm.time = dayjs().format('YYYY-MM-DD');
    fetchAllData()
})
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.mt-2 {
    margin-top: 20px;
}

.site-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
}

h3 {
    font-weight: bold;
    font-size: 18px;
    margin-bottom: 10px;
}

.num {
    font-size: 30px;
    font-weight: bold;
}

.loading-circle {
    margin-left: 20px;
}
</style>